import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { PageResultDto } from 'src/common/dto';
import { Role } from '../role/entities/role.entity';
import { Company } from '../company/entities/company.entity';
import { Dept } from '../dept/entities/dept.entity';
import { Duty } from '../duty/entities/duty.entity';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>
  ) {}
  create(createUserDto: CreateUserDto) {
    return 'This action adds a new user';
  }

  // findAll() {
  //   return `This action returns all user`;
  // }

  async findAll(querylistDto: any): Promise<PageResultDto<User>> {
    let users = await this.usersRepository.createQueryBuilder('user')
      .leftJoinAndSelect('user.Role', 'Role')
      .skip((querylistDto.pageNum - 1) * querylistDto.pageSize)
      .take(querylistDto.pageSize)
      .getMany();
    
    let result = new PageResultDto<User>();
    result.data = users;
    result.total = await this.usersRepository.count();
    result.pageNum = querylistDto.pageNum;
    result.pageSize = querylistDto.pageSize;
    return result;
  }

  async findOne(id: string):  Promise<[boolean, User]> {
    let user = await this.usersRepository.findOne({ where: { Id: id } });
    console.log(user.Password)
    if (!user) {
      return [false, new User()];
    }
    // console.log('查询用户成功', user);
    return [true, user];
  }

  async findOneByUsername(username: string): Promise<[boolean, User]> {
    let user = await this.usersRepository.findOne({ where: { UserName: username }, relations: ['Role'] });
    if (!user) {
      return [false, new User()];
    }
    console.log('查询用户成功', user);
    return [true, user];
  }

  async update(updateUserDto: CreateUserDto):  Promise<[boolean, string]> {
    let user = await this.usersRepository.findOne({ where: { Id: updateUserDto.Id }, relations: ['Role'] });
    if (!user) {
      return [false, "更新失败，用户不存在"];
    }
    // 更新用户信息
    user = this.usersRepository.create(updateUserDto);
    const role = new Role();
    role.Id = updateUserDto.roleId;
    const company = new Company();
    company.Id = updateUserDto.companyId;
    const dept = new Dept();
    dept.Id = updateUserDto.deptId;
    const duty = new Duty();
    duty.Id = updateUserDto.dutyId;
    await this.usersRepository.update(user.Id, {
      Phone: user.Phone,
      Status: user.Status,
      RealName: user.RealName,
      Role: role,
      Company: company,
      Dept: dept,
      Duty: duty,
    });
    return [true, "更新成功"];
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
  async register(createUserDto: CreateUserDto) {
    try {
      // 检查必填字段
      if (!createUserDto.UserName || !createUserDto.Password) {
        throw new Error('用户名和密码是必填字段');
      }
    } catch (error) {
      console.error('注册失败:', error.message); 
    }
    // 这里可以添加注册逻辑，比如保存用户到数据库
    // console.log('注册用户', createUserDto);
    let username = createUserDto.UserName;
    const existUset = await this.usersRepository.findOne({ where: { UserName: username } });
    if (existUset) {
      console.log('用户已存在');
      return "用户已存1";
    }
    const role = new Role();
    role.Id = createUserDto.roleId;
    const company = new Company();
    company.Id = createUserDto.companyId;
    const dept = new Dept();
    dept.Id = createUserDto.deptId;
    const duty = new Duty();
    duty.Id = createUserDto.dutyId;
    const user = this.usersRepository.create(createUserDto);
    user.Role = role;
    user.Company = company;
    user.Duty = duty;
    user.Dept = dept;
    console.log(user);
    await this.usersRepository.save(user);
    console.log('用户注册成功');
    return user;
  }
}
